import {defineStore} from "pinia";
import {ref} from "vue";
import {getMenus} from "@/api/system/SysMenuApi.js";
import router, {asyncRoutes} from "@/router/index.js";

export const useMenu = defineStore("menu", () => {
    const menu = ref([]);
    const allMenus = ref([]);
    const isCollapse = ref(false);

    const generateUrl = (path, parentPath) => {
        return path.startsWith("/") ? path : path ? `${parentPath}/${path}` : parentPath;
    }
    const getFilterRoutes = (targetRoutes = [], ajaxRoutes = []) => {
        const filterRoutes = [];
        ajaxRoutes.forEach(ajaxRoute => {
            const target = targetRoutes.find(item => item.name === ajaxRoute.componentCode);
            if (target) {
                const {children, ...rest} = target;
                const route = {
                    ...rest
                };
                if (children) {
                    // 同级对比
                    route.children = getFilterRoutes(children, JSON.parse(JSON.stringify(ajaxRoute.children)));
                }
                filterRoutes.push(route);
            }
        })

        return filterRoutes;
    }

    const getFilterMenus = (routes, parentPath = '') => {
        const filterMenus = [];
        routes.forEach(route => {
            if (!route.hidden) {
                const menuModel = {
                    url: generateUrl(route.path, parentPath),
                    title: route.meta?.title,
                    icon: route.meta?.icon
                }
                if (route.children) {
                    menuModel.children = getFilterMenus(route.children, route.path);
                }
                filterMenus.push(menuModel);
            }
        })

        return filterMenus;
    }
    const generateMenus = async () => {
        const list = await getMenus();
        // 添加动态路由之前先删除
        asyncRoutes.forEach(route => router.removeRoute(route.name))
        const filterRoutes = getFilterRoutes(asyncRoutes, list);
        filterRoutes.forEach(route => router.addRoute(route));
        allMenus.value = list;
        menu.value = getFilterMenus([...filterRoutes]);
    }

    const changeCollapse = ()=> isCollapse.value = ! isCollapse.value;

    return {
        menu,
        allMenus,
        isCollapse,
        generateMenus,
        changeCollapse
    }
})

